class Solution:
    def checkIfPrerequisite(self, n: int, prerequisites: list,
                            queries: list) -> list:
        def func(adj, node, cache):
            if node in cache:
                return cache[node]
            arr = []
            for n in adj[node]:
                arr.append(n)
                arr += func(adj, n, cache)
            cache[node] = set(arr)
            return arr

        adj = [[] for _ in range(n)]
        for prerequisite in prerequisites:
            adj[prerequisite[0]] += [prerequisite[1]]

        cache = {}
        for i in range(n):
            func(adj, i, cache)
        res = []
        for query in queries:
            if query[0] in cache:
                res += [query[1] in cache[query[0]]]
            else:
                res += [False]

        return res
